<?php
include_once 'fns_db.php';
include_once 'fns.php';
include_once 'valid_fns.php';

session_start();

if (isset($_GET['term'])) {
    $term=$_GET['term'];
    $answer=get_answer($term);
    echo $answer;
}

function get_answer($term){
    $admin_mod=FALSE;
    if (check_valid_user() && check_valid_session()){
        $admin_mod=TRUE;
    }     
    $query="select t1.id, t1.name as 'emp',t6.name as 'post',t3.number, t5.name as 'org', t1.email as 'email', t4.name as 'dep' from `emp` as t1 
    join `tel_emp` as t2  on t1.id=t2.id_emp
    join `tel` as t3 on t2.id_tel=t3.id
    left join `dep` as t4 on t1.id_dep=t4.id
    left join `org` as t5 on t4.id_org=t5.id
    left join `post` as t6 on t6.id=t1.id_post
    where t3.typenumber!=3 and (
        t1.name like \"%{$term}%\"
        or t6.name like \"%{$term}%\"
        or t3.number like \"%{$term}%\"
        or t5.name like \"%{$term}%\"
        or t1.email like \"%{$term}%\"
        or t4.name like \"%{$term}%\"
    ) ";
        if ($admin_mod!==TRUE) $query.=" and t3.visible=1 ";
    $query.=" order by t1.name asc, t3.typenumber desc, t3.number asc";
    $data=get_data_from_table_assoc($query);
    
    if ($data===FALSE) { echo 'Не найти'; exit();}
    $data=modify_emp_tel_array($data);
    formated_tel_array2($data, 'number');
    format_email($data);
    $c=count($data);
    
    $str.='[{"value": "'.$data[0]['emp'].
            ' - '.$data[0]['post'].
            ' - '.$data[0]['org'].
            ' - '.$data[0]['dep'].
            ' - '.strip_tags($data[0]['number']).
            '",';
    $str.='"desc":"'.$data[0]['id'].'"}';
    for ($i=1; $i<$c;$i++) {
        $str.=',{"value": "'.$data[$i]['emp'].
                ' - '.$data[$i]['post'].
                ' - '.$data[$i]['org'].
                ' - '.$data[$i]['dep'].
                ' - '.strip_tags($data[$i]['number']).
                '",';
        $str.='"desc":"'.$data[$i]['id'].'"}';
    }
    $str.=']';
    echo $str;
}

?>
